<template>
    <div>
        <van-popup v-model="myShow" position="bottom">
            <div>
                <div class="search-wrap">
                    <van-search v-model="value" placeholder="请输入搜索关键词" @search="onSearch" @clear="onSearch"></van-search>
                </div>
                <ul class="list-wrap">
                    <li class="item-wrap" @click="onSelect(index)" :class="{height0: hideList.indexOf(item)>= 0}" v-for="(item,index) in list" :key="index">
                        <div class="item-box">
                            {{item}}
                        </div>
                    </li>
                </ul>
            </div>
        </van-popup>
    </div>
</template>

<script>
 import {Popup,Search } from 'vant'
  export default {
    name: "m-select",
    components: {
      [Popup.name]: Popup,
      [Search.name]: Search
    },
    model: {
      prop: 'show',
      event: 'myEvent'
    },
    props: {
      show: {},
      options: {},
      entityKey: {
        default: 'name'
      }
    },
    watch: {
      show(val){
        this.myShow = val;
      },
      myShow(val){
        this.$emit('myEvent',val);
      },
      options: {
        handler(val){
          let {entityKey} = this,
            list = [];
          console.log(val,entityKey);
          if (val && val.length){
            if (typeof val[0] === 'string')list = val;
            else {
              val.forEach(item => {
                list.push(item[entityKey]);
              })
            }
            this.list = list;
          }
        },
        immediate: true
      }
    },
    data(){
      return {
        myShow: false,
        list: [],
        value: '',
        hideList: []
      }
    },
    methods: {
      onSearch(){
        let {list,value} = this,
          hideList = [];
        value && list.forEach(item => {
          item.indexOf(value) >= 0 && hideList.push(item);
        });
        this.hideList = hideList;
      },
      onSelect(index){
        let {options} = this,
          item = options[index];
        this.myShow = false;
        this.$emit('select',item);
      }
    }
  }
</script>

<style scoped lang="less">
    .search-wrap{
        box-shadow: 0 1px 9px rgba(0,0,0,0.1);
    }
    .list-wrap{
        height: 260px;
        overflow: auto;
        .item-wrap{
            padding: 0 10px;
            height: 40px;
            transition: all 0.3s linear 0s;
            .item-box{
                height: 100%;
                border-bottom: 1px solid #ededed;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 16px;
            }
            &.height0{
                height: 0;
                opacity: 0;
                overflow: hidden;
            }
        }
    }
</style>
